﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Common;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helpers;
using Ultimus.OC;
using Ultimus.WFServer;
using UServLib;

namespace H2.NET.Web.Workflow.Workflow
{
    public partial class BatchApprove : BasePage
    {
        #region 属性 public

        private DataTable dt = new DataTable();

        [SessionType]
        string strProcessName = "";

        //类型
        public string Type
        {
            get
            {
                return this.ViewState["Type"] == null ? "" : (String)this.ViewState["Type"];
            }
            set
            {
                this.ViewState["Type"] = value;
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            var action = AksRequest.GetQueryStringValue("action");
            if (string.IsNullOrEmpty(action)) //默认页面加载
            {
                try
                {
                    load_gv_inbox_list();
                }
                catch (Exception ee)
                {
                    TaskDB.Log("", false, "调用 BatchApprove.aspx 页面 Page_Load 事件出错：" + ee.Message);
                }
            }
            else if (action == "approve_selected") //审核选中的任务
            {
                var taskIds = AksRequest.GetString("ids");
                var aryTaskIds = string.IsNullOrEmpty(taskIds) ? new string[0] : taskIds.Split(',');
                foreach (var taskId in aryTaskIds)
                {
                    clsCmm.clsDB.Storage("bpmDB");
                    var dtTask = clsCmm.clsDB.Query("SELECT [PROCESSNAME] ,[INCIDENT] ,[STEPID] ,[STEPLABEL] ,[RECIPIENT] ,[RECIPIENTTYPE] ,[TASKUSER] ,[ASSIGNEDTOUSER] ,[STATUS] FROM [TASKS] where TASKID = '" + taskId.Replace("'", "''") + "'");
                    if (dtTask.Rows.Count > 0)
                    {
                        var processName = dtTask.Rows[0]["PROCESSNAME"].ToString().Trim();
                        var processStep = dtTask.Rows[0]["STEPLABEL"].ToString().Trim();
                        var processIncident = dtTask.Rows[0]["INCIDENT"].ToString().Trim();

                        clsCmm.clsDB.Storage("oleDB");
                        var dtAssessmentOption = clsCmm.clsDB.Query("SELECT Process, Step, OptionName, OptionValue, isReturned, isBatch, SetVariable, DataProcess, Status FROM t_AssessmentOptions WHERE (Status = '1') AND (isBatch = 'Y') AND Process = '" + processName + "' AND Step = '" + processStep + "'");
                        if (dtAssessmentOption.Rows.Count > 0)
                        {
                            var dtVariable = clsCmm.clsDB.Query(dtAssessmentOption.Rows[0]["SetVariable"].ToString() + " '" + taskId + "'");
                            var dataProcess = dtAssessmentOption.Rows[0]["DataProcess"].ToString();
                            if (dtVariable.Rows.Count > 0)
                            {
                                var variables = new Variable[dtVariable.Rows.Count];
                                for (int i = 0; i < dtVariable.Rows.Count; i++)
                                {
                                    var variable = new Variable
                                    {
                                        strVariableName = dtVariable.Rows[i][0].ToString(),
                                        objVariableValue = dtVariable.Rows[i][1].ToString().Split('|')
                                    };
                                    variables[i] = variable;
                                }

                                var taskApi = new TaskAPI();
                                clsCmm.clsDB.ExcuteSql(
                                    string.Format(
                                        "INSERT INTO [t_Assessment]([ID],[Process],[Incident],[Step],[UserName],[UserFullName],[AssignedToUserName],[AssignedToUserFullName],[Department],[Signature],[Opinion],[Opinion2],[OpinionText],[OpinionText2],[Remark],[StartTime],[Time],[Status],[Attitude]) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}')"
                                        , DateTime.Now.ToString("yyyyMMddHHmmss") + (new Random()).Next(1000, 9999), processName,
                                        processIncident, processStep, taskApi.UserName, taskApi.UserFullName, clsCmm.comm_username,
                                        clsCmm.comm_userfullname, clsCmm.comm_userdepartment, clsCmm.comm_mail,
                                        dtAssessmentOption.Rows[0]["OptionValue"].ToString(), dtAssessmentOption.Rows[0]["OptionValue"].ToString(),
                                        dtAssessmentOption.Rows[0]["OptionName"].ToString(), dtAssessmentOption.Rows[0]["OptionName"].ToString(), "",
                                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "1", "Batch Approved"));

                                taskApi.SubmitApprove(taskId, variables, int.Parse(processIncident));

                                if (dataProcess != "") clsCmm.clsDB.ExcuteSql(dataProcess + " '" + taskId + "'");

                            }
                        }
                    }
                }

                WriteToClient("true");
            }
        }

        public void load_gv_inbox_list()
        {
            try
            {
                //加载列表
                dt = get_all_inbox();

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region added by zk 2009-12-21 start
                //取得所有的用户账号对应用户姓名             
                string str_user_name = "";
                DataTable dt2 = new DataTable();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //initiator
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'";
                    }

                    //taskuser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'";
                    }

                    //assignedtouser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'";
                    }
                }

                //从数据库中查询用户信息
                string strSQL = "select rtrim(FULLNAME) as UserFullName,lower(rtrim(Name)) as UserShortName from JOBS where lower(rtrim(Name)) in('-1'" + str_user_name + ")";
                clsCmm.clsDB.Storage("bpmDB");
                dt2 = clsCmm.clsDB.Query(strSQL);
                #endregion added by zk 2009-12-21 end

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //处理表单类型 (自定义表单 & 标准表单)
                    string HelpUrl = dt.Rows[i]["helpurl"].ToString();

                    Dictionary<string, string> parms = new Dictionary<string, string>();
                    parms.Add("taskId", dt.Rows[i]["taskid"].ToString());
                    parms.Add("incident", dt.Rows[i]["incident"].ToString());

                    dt.Rows[i]["openform"] = UltimusHelper.ResolveUrl(dt.Rows[i]["helpurl"].ToString().Trim(),
                                                                    parms,
                                                                    dt.Rows[i]["processname"].ToString().Trim());

                    #region added by zk 2009-12-21 start
                    //循环设置用户信息
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        //initiator
                        if (dt.Rows[i]["initiator"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["initiator_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //taskuser
                        if (dt.Rows[i]["taskuser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["taskuser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //assignedtouser
                        if (dt.Rows[i]["assignedtouser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["assignedtouser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }
                    }
                    #endregion added by zk 2009-12-21 end

                    //流程状态图标
                    switch (dt.Rows[i]["substatus"].ToString().Trim())
                    {
                        case "0":
                        case "1":
                            dt.Rows[i]["img_status"] = "frm_inbox_late.gif";
                            break;

                        case "2":
                            dt.Rows[i]["img_status"] = "frm_inbox_overdue.gif";
                            break;

                        case "3":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "4":
                            dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                            break;

                        case "7":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "8":
                            dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                            break;

                        case "16":
                            dt.Rows[i]["img_status"] = "frm_inbox_returned.gif";
                            break;

                        case "32":
                            dt.Rows[i]["img_status"] = "frm_inbox_resubmitted.gif";
                            break;

                        default:
                            dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                            break;
                    }

                    //判断是否为指派、会办的任务类型
                    if (dt.Rows[i]["taskuser"].ToString() != dt.Rows[i]["assignedtouser"].ToString())
                    {
                        dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                    }

                    //是否显示监控图标
                    if (dt.Rows[i]["taskid"] == DBNull.Value || dt.Rows[i]["taskid"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["img_monitor"] = "frm_initiate_blank.gif";
                        dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                    }
                    else
                    {
                        dt.Rows[i]["img_monitor"] = "bpmview.gif";
                    }

                }

                //第一次没有排序字段的情况
                if (ViewState["OrderBy"] == null)
                {
                    dt.DefaultView.Sort = "starttime DESC";
                }
                else
                {
                    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                }

                gvInbox.DataSource = dt;
                gvInbox.DataBind();

            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_gv_inbox_list 方法出错：" + ee.Message);
            }
        }

        public DataTable get_all_inbox()
        {
            try
            {
                string strSQL = "";
                string strUserName = clsCmm.comm_username;
                string strSummary = ""; //tb_Summary.Text.Trim().Replace(",", "',").Replace("'", "''");
                string strIncidentNoFrom = "";// txtIncidentFrom.Text.Trim().Replace(".", "");
                string strIncidentNoTo = "";// txtIncidentTo.Text.Trim().Replace(".", "");

                //查询过滤中Process下拉列表中的值
                string strProcess = "all";
                //if (drpProcess.SelectedItem != null)
                //{
                //    strProcess = drpProcess.SelectedItem.Value.Trim();
                //}

                //string strStep = "all";
                //if (drpStep.SelectedItem != null)
                //{
                //    strStep = drpStep.SelectedItem.Value.Trim();
                //}

                //查找收件箱列表
                strSQL = "";
                strSQL += "select distinct d.*,";
                strSQL += "       '' as initiator_name,";
                strSQL += "       '' as taskuser_name,";
                strSQL += "       '' as assignedtouser_name";
                strSQL += "  from (select b.*, c.summary, c.priority, c.initiator";
                strSQL += "          from (select rtrim(a.taskid) as taskid";
                //中文的情况，流程名变化
                if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
                {
                    strSQL += " ,h.processhelpurl as processname3";
                    strSQL += " ,h.processname";
                }
                else
                {
                    strSQL += " ,a.processname as processname3";
                    strSQL += " ,a.processname";
                }

                strSQL += " ,rtrim(a.helpurl) as helpurl";
                strSQL += " ,'' as openform";

                strSQL += " ,a.incident";
                strSQL += " ,a.steplabel";
                strSQL += " ,a.taskuser";
                strSQL += " ,a.assignedtouser";
                strSQL += " ,'' as img_status";     //状态图标
                strSQL += " ,'' as img_monitor";    //监控图标
                strSQL += " ,a.status";
                strSQL += " ,a.substatus";
                strSQL += " ,a.starttime";
                strSQL += " ,a.delaytime";
                strSQL += " ,a.overduetime";
                strSQL += " ,a.urgentduetime";

                strSQL += " from tasks a WITH (NOLOCK) , initiate h WITH (NOLOCK) ";    //with(readpast,rowlock)
                strSQL += " where 1=1 and a.processname=h.processname AND H.PROCESSNAME IN(SELECT [PROCESSNAME] FROM [PROCESSES] WHERE [PROCESSES].[DESCRIPTION] IN (SELECT KeyWords FROM BPMSYSTEM WHERE Platform = '" + Util.AppSettings("platform") + "')) ";
                strSQL += " and a.taskid not in(select taskid from taskqueue)";

                //batch approve
                strSQL += " and (a.PROCESSNAME in(" + GetProcess().ProcessName + ") and a.STEPLABEL in(" + GetProcess().Step + ")) ";
                strSQL += " and a.taskuser = '" + strUserName + "'  COLLATE Chinese_PRC_CI_AI";
                strSQL += " and a.assignedtouser = '" + strUserName + "'  COLLATE Chinese_PRC_CI_AI";
                strSQL += " and a.status = 1";

                //如果 Type=1 的情况,则表示我的审批   Type=2 的情况,则表示我的申请
                if (this.Type == "1")
                {
                    strSQL += " and right(rtrim(a.stepid),1) <> 'B'";
                }
                else if (this.Type == "2")
                {
                    strSQL += " and right(rtrim(a.stepid),1) = 'B'";
                }


                //查询过滤
                if (strProcess != "all")
                {
                    strSQL = strSQL + " and a.processname = '" + strProcess + "'";
                }

                //added by
                if (!string.IsNullOrEmpty(strProcessName))
                {
                    strSQL = strSQL + " and a.processname = '" + strProcessName + "'";
                }

                //if (strStep != "all")
                //{
                //    strSQL = strSQL + " and a.steplabel = '" + strStep + "'";
                //}

                if (strIncidentNoFrom != "")
                {
                    strSQL = strSQL + " and a.incident >= " + strIncidentNoFrom + "";
                }

                if (strIncidentNoTo != "")
                {
                    strSQL = strSQL + " and a.incident <= " + strIncidentNoTo + "";
                }

                strSQL += " ) b";
                strSQL += " left join incidents c on b.processname = c.processname";
                strSQL += " and b.incident = c.incident) d";

                //摘要
                if (strSummary != "")
                {
                    strSQL = strSQL + " where d.summary like '%" + strSummary + "%'";
                }

                TaskDB.Log("", true, "调用 inbox.aspx 页面 get_all_inbox 方法SQL：" + strSQL);
                clsCmm.clsDB.Storage("bpmDB");
                dt = clsCmm.clsDB.Query(strSQL);

                return dt;
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 get_all_inbox 方法出错：" + ee.Message);
                return null;
            }
        }

        struct IsBench
        {
            public string ProcessName;
            public string Step;
        }

        private IsBench GetProcess()
        {
            var isBatch = new IsBench { ProcessName = "''", Step = "''" };

            clsCmm.clsDB.Storage("oleDB");
            dt = clsCmm.clsDB.Query("SELECT Process,Step FROM t_AssessmentOptions WHERE ISBATCH = 'Y' AND STATUS = '1'");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                isBatch.ProcessName += ", '" + dt.Rows[i][0].ToString() + "'";
                isBatch.Step += ", '" + dt.Rows[i][1].ToString() + "'";
            }
            return isBatch;
        }

    }
}